import {Modal, Radio, RadioChangeEvent, Table, Tag} from 'antd';
import React, {useEffect, useState} from 'react';
import type {ColumnsType} from 'antd/lib/table/interface';
import type {MoteInfoItem} from './data';
import {queryHistoryList} from './service';
import {DeviceMessageType} from "@/pages/Device/Locker/History/data";

interface EditFormProps {
  // 规则的唯一id
  deviceNo: string;
  // 类型
  type: string;
  // 请求修改数据的回调
  onSubmit: (flag?: boolean) => void;
  // 取消窗口的回调
  onCancel: (flag?: boolean) => void;
  // 窗口是否可见
  modalVisible: boolean;
}

interface PaginationConfig {
  page: number;
  pageSize: number;
  total: number;
}

const MoteInfoListModal: React.FC<EditFormProps> = props => {
  const [dataStatusList, setDataStatusList] = useState<MoteInfoItem[] | undefined>(undefined);
  const [dataInfo, setDataInfoList] = useState<MoteInfoItem[] | undefined>(undefined);
  const [loading, setLoading] = useState<boolean>(false);
  const [type, setType] = useState<DeviceMessageType>('status');
  const [pageObject, setPageObject] = useState<PaginationConfig>({
    page: 1,
    pageSize: 10,
    total: 0,
  });

  const {deviceNo, onCancel: handleEditModalVisible, modalVisible: editModalVisible} = props;

  const columnsStatus: ColumnsType<MoteInfoItem> = [
    {
      title: '记录时间',
      dataIndex: 'createAt',
      render: (_, record) => <Tag>{record.createAt}</Tag>,
    },
    {
      title: '状态计数',
      dataIndex: 'count',
      render: (_, record) => <Tag>{record.count}</Tag>,
    },
    {
      title: '信号强度',
      dataIndex: 'rtRssi',
      render: (_, record) => <Tag>{record.rtRssi}</Tag>,
    },
    {
      title: '信噪比',
      dataIndex: 'rtSnr',
      render: (_, record) => <Tag>{record.rtSnr}</Tag>,
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (_, record) =>
          record.statusList?.map(status => <Tag color={status?.color}>{status?.label}</Tag>),
    },
    {
      title: '状态更新时间',
      dataIndex: 'stateUpdateAt',
      render: (_, record) => <Tag>{record.stateUpdateAt}</Tag>,
    },
  ];

  const columnsInfo: ColumnsType<MoteInfoItem> = [
    {
      title: '记录时间',
      dataIndex: 'createAt',
      render: (_, record) => <Tag>{record.createAt}</Tag>,
    },
    {
      title: '电池电压',
      dataIndex: 'batt',
      render: (_, record) => <div>{record.batt}</div>,
    },
    {
      title: 'IMEI',
      dataIndex: 'imei',
      render: (_, record) => <div>{record.imei}</div>,
    },
    {
      title: 'SIM号',
      dataIndex: 'sim',
      render: (_, record) => <div>{record.sim}</div>,
    },
    {
      title: '温度',
      dataIndex: 'temp',
      render: (_, record) => <div>{record.temp}</div>,
    },
  ];

  const request = async (id: string, type: DeviceMessageType, page?: number, pageSize?: number): Promise<{
    success: boolean;
    total: number;
    pageCount?: number;
    data: MoteInfoItem[] | null;
  }> => {
    const data = await queryHistoryList({
      deviceNo: id,
      type,
      page: page || 1,
      pageSize: pageSize || pageObject.pageSize || 10,
    });
    if (data.success) {
      setPageObject({...pageObject, total: data.total, page: page || 1});
    } else {
      setPageObject({...pageObject, total: 0, page: 1});
    }
    return data;
  };

  useEffect(() => {
    if (!deviceNo) throw new Error('ruleId 不能为空');
    setLoading(true);
    request(deviceNo, 'status', 1)
    .then(res => {
      if (res.success && res.data !== null) {
        setDataStatusList(res.data); // datalist必须为[]
        setLoading(false);
      }
    })
    .finally(() => {
    });
  }, []);

  const handleReload = async (page?: number) => {
    setLoading(true);
    request(deviceNo, type, page)
    .then(res => {
      if (res.success && res.data !== null) {
        switch (type) {
          case 'status': // 状态
            setDataStatusList(res.data);
            setDataInfoList(undefined);
            setLoading(false);
            break;
          case 'info': // 工作
            setDataInfoList(res.data);
            setDataStatusList(undefined);
            setLoading(false);
            break;
          default:
            break;
        }
      }
    })
    .finally(() => {
    });
  };

  const radioChange = (e: RadioChangeEvent) => {
    const selectedType: DeviceMessageType = e.target.value;
    setType(selectedType);

    setLoading(true);
    setPageObject({...pageObject, page: 1, pageSize: 10});

    request(deviceNo, selectedType)
    .then(res => {
      if (res.success && res.data !== null) {
        switch (selectedType) {
          case 'status': // 状态
            setDataStatusList(res.data);
            setDataInfoList(undefined);
            setLoading(false);
            break;
          case 'info': //
            setDataInfoList(res.data);
            setDataStatusList(undefined);
            setLoading(false);
            break;
          default:
            break;
        }
      }
    })
    .finally(() => {
    });
  };

  return (
      <Modal
          title={<div>设备{deviceNo} &nbsp;历史数据</div>}
          visible={editModalVisible}
          destroyOnClose
          width={1200}
          onOk={() => handleEditModalVisible(false)}
          onCancel={() => handleEditModalVisible(false)}
          afterClose={() => handleEditModalVisible(false)}
          okText="确定"
          cancelText="取消"
      >
        <span style={{marginRight: '10px'}}>记录类型选择:</span>
        <Radio.Group name="radio_group" defaultValue="status" onChange={radioChange}>
          <Radio value="status">状态包</Radio>
          <Radio value="info">信息包</Radio>
        </Radio.Group>
        {/*<Button style={{marginLeft: '820px'}} type="primary" onClick={() => handleReload()}>*/}
        {/*  <ReloadOutlined/> 刷新*/}
        {/*</Button>*/}
        {dataStatusList && (
            <Table
                columns={columnsStatus}
                dataSource={dataStatusList}
                rowKey="createAt"
                loading={loading}
                style={{marginTop: '20px'}}
                pagination={{
                  ...pageObject,
                  onChange: (page, pageSize) => {
                    setPageObject({...pageObject, page, pageSize: pageSize || 10});
                    handleReload(page);
                  },
                }}
            />
        )}
        {dataInfo && (
            <Table
                columns={columnsInfo}
                dataSource={dataInfo}
                rowKey="createAt"
                loading={loading}
                style={{marginTop: '20px'}}
            />
        )}
      </Modal>
  );
};
export default MoteInfoListModal;
